package org.jeecgframework.web.controller;

import com.fr.base.StringUtils;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.service.*;
import org.jeecgframework.web.service.impl.ZyInspectionPlanServiceImpl;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by red on 2016/9/26.
 */
@Controller
@RequestMapping("/inspectionWx")
public class CbsInspectionWxController {

    private final static Logger logger = Logger.getLogger(CbsInspectionWxController.class);

    private static final String PREFIX = "com/wx/added_product";

    @Autowired
    private ZyContactsServiceI zyContractsService;

    @Autowired
    private CbsInspectionEvaluateServiceI cbsInspectionEvaluateService;

    @Autowired
    private ZyEquipmentSpareServiceI zyEquipmentSpareService;

    @Autowired
    private CbsInspectionAppointmentServiceI cbsInspectionAppointmentService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private ZyWorkFlowService zyWorkFlowService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ZyPlanRecordServiceI zyPlanRecordService;

    @Autowired
    private ZyInspectionPlanServiceI zyInspectionPlanService;

    /**
     * 跳转到我的巡检
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "goMyInspectionList")
    public ModelAndView goMyInspectionList(ModelMap modelMap, HttpServletRequest request) {
        TSUser user = ResourceUtil.getSessionUserName();

        if (user == null || !user.ifGoldMedal()) {
            return new ModelAndView("redirect:wxMenuController.do?ordList&type=" + WxCommonService.ServiceEnum.XJYY.type);
        }

        //TODO 巡检预约
        List<CbsInspectionAppointmentEntity> inspectionApp = systemService.findHql("from CbsInspectionAppointmentEntity where createName = ?", user.getUserName());
        //我的巡检单
        ZyContactsEntity contacts = zyContractsService.findContactByUserName(user.getUserName());
        /*if (StringUtil.isNotEmpty(contacts) && StringUtil.isNotEmpty(contacts.getBelongCinema())) {
            List<ZyEquipmentSpareEntity> esList = systemService.findHql("from ZyEquipmentSpareEntity where zyCinema.id = ?", contacts.getBelongCinema().getId());
            String esIdStr = "";
            for (ZyEquipmentSpareEntity es : esList) {
                esIdStr += es.getId() + ",";
            }
            if (StringUtil.isNotEmpty(esIdStr)) {
                esIdStr = esIdStr.substring(0, esIdStr.length() - 1).replace(",", "','");
                List<ZyInspectionPlanEntity> inspectionPlanList = systemService.findHql("from ZyInspectionPlanEntity where equipmentSpare.id in ('" + esIdStr + "')");
                request.setAttribute("inspectionPlanList", inspectionPlanList);
            }
        }*/
        if (contacts.getBelongCinema() != null) {
            List<ZyInspectionPlanEntity> plans = zyInspectionPlanService.queryPlanWithCinemaAndYear(contacts.getBelongCinema().getId(), "");
            modelMap.put("plans", plans);
        }
        return new ModelAndView("com/wx/personal_center/my_inspection/my_inspectionList");
    }

    @RequestMapping(params = "evaluate")
    public ModelAndView goVealuateDesc(String id) {
        ModelAndView mv = new ModelAndView("com/wx/personal_center/my_inspection/inspection_evaluate_detail");
        CbsInspectionEvaluateEntity evaluateEntity = systemService.get(CbsInspectionEvaluateEntity.class, oConvertUtils.getString(id));
        mv.addObject("evaluate", evaluateEntity);
        return mv;
    }

    @RequestMapping(params = "goPcEvaluateDetail")
    public ModelAndView goPcEvaluateDetail(String id) {
        ModelAndView mv = null;
        String zyCinemaName = "";/*影院名称*/
        String zyCinemaAddress = "";/*影院地址*/
        String endTime = "";/*完成时间*/
        String engineer = "";/*工程师*/
        String departname = "";/*服务商*/
        boolean f = false;
        SimpleDateFormat sf = new SimpleDateFormat("YYYY-MM-dd");
        CbsInspectionEvaluateEntity evaluateEntity = systemService.get(CbsInspectionEvaluateEntity.class, oConvertUtils.getString(id));
        if (evaluateEntity.getBusType().equals(StaticValue.DIC_EVALUATE_BUS_TYPE_1)) {  //巡检
            mv = new ModelAndView("com/wx/personal_center/my_inspection/pc_evaluate_detail");
            if (evaluateEntity != null && !StringUtils.isEmpty(evaluateEntity.getInspection().getCompany())) {
                List<TSDepart> departs = cbsInspectionAppointmentService.findHql("from TSDepart where orgCode=?", evaluateEntity.getInspection().getCompany());
                if (departs.size() > 0) {
                    mv.addObject("depart", departs.get(0));
                }
            }
        }
        if (evaluateEntity.getBusType().equals(StaticValue.DIC_EVALUATE_BUS_TYPE_2)) {  //维修
            f = true;
            mv = new ModelAndView("com/wx/personal_center/my_inspection/pc_servicing_detail");
        }
        if (evaluateEntity.getBusType().equals(StaticValue.DIC_EVALUATE_BUS_TYPE_3)) {  //投诉
            f = true;
            mv = new ModelAndView("com/wx/personal_center/my_inspection/pc_complain_detail");
        }
        if (evaluateEntity.getBusType().equals(StaticValue.DIC_EVALUATE_BUS_TYPE_4)) {  //其他
            f = true;
            mv = new ModelAndView("com/wx/personal_center/my_inspection/pc_other_detail");
        }
        if (f && StringUtil.isNotEmpty(evaluateEntity)) {
            if (StringUtil.isNotEmpty(evaluateEntity.getCbsService())) {   /*默认生成的服务单，服务单id肯定不为空*/
                zyCinemaName = evaluateEntity.getCbsService().getZyCinemaName();
                zyCinemaAddress = evaluateEntity.getCbsService().getAddress();
                endTime = StringUtil.isNotEmpty(evaluateEntity.getCbsService().getCloseTime()) ? sf.format(evaluateEntity.getCbsService().getCloseTime()) : "";
                engineer = StringUtil.isNotEmpty(evaluateEntity.getCbsService().getEngineer()) ? systemService.get(ZyEngineerEntity.class, evaluateEntity.getCbsService().getEngineer()).getName() : "";
                departname = StringUtil.isNotEmpty(evaluateEntity.getCbsService().getZyContacts()) ? systemService.get(ZyContactsEntity.class, evaluateEntity.getCbsService().getZyContacts()).getBelongOrg().getDepartname() : "";
            } else if (StringUtil.isNotEmpty(evaluateEntity.getCbsCode())) {  /*手动创建的服务单，服务单id为空，服务单code不为空*/
                CbsServiceEntity cbsServiceEntity = systemService.findUniqueByProperty(CbsServiceEntity.class, "code", evaluateEntity.getCbsCode());
                if (StringUtil.isNotEmpty(evaluateEntity.getCinemaName())) {
                    ZyCinemaEntity zyCinemaEntity = systemService.get(ZyCinemaEntity.class, evaluateEntity.getBelongCinemaId());
                    zyCinemaName = zyCinemaEntity.getName();
                    zyCinemaAddress = zyCinemaEntity.getAddress();
                }
                if (StringUtil.isNotEmpty(cbsServiceEntity)) {
                    endTime = StringUtil.isNotEmpty(cbsServiceEntity.getCloseTime()) ? sf.format(cbsServiceEntity.getCloseTime()) : "";
                    engineer = StringUtil.isNotEmpty(cbsServiceEntity.getEngineer()) ? systemService.get(ZyEngineerEntity.class, cbsServiceEntity.getEngineer()).getName() : "";
                    departname = StringUtil.isNotEmpty(cbsServiceEntity.getZyContacts()) ? systemService.get(ZyContactsEntity.class, cbsServiceEntity.getZyContacts()).getBelongOrg().getDepartname() : "";
                }
            } else {  /*手动创建的服务单，服务单code为空的情况*/
                zyCinemaName = evaluateEntity.getCinemaName();

                //查询影院地址
                List<ZyCinemaEntity> zyCinemaEntity = systemService.findByQueryString("from ZyCinemaEntity where name like '%" + zyCinemaName + "%'");
                if (zyCinemaEntity.size() > 0) {
                    zyCinemaAddress = zyCinemaEntity.get(0).getAddress();
                }

            }
            mv.addObject("zyCinemaName", zyCinemaName);
            mv.addObject("zyCinemaAddress", zyCinemaAddress);
            mv.addObject("endTime", endTime);
            mv.addObject("engineer", engineer);
            mv.addObject("departname", departname);
        }
        mv.addObject("evaluate", evaluateEntity);
        return mv;
    }

    @RequestMapping(params = "goEvaluate")
    public ModelAndView goEvaluate(HttpServletRequest request) {
        ModelAndView mv = null;
        String type = request.getParameter("busType");
        String id = request.getParameter("id");
        String zyCinemaName = "";/*影院名称*/
        String zyCinemaAddress = "";/*影院地址*/
        String endTime = "";/*完成时间*/
        String engineer = "";/*工程师*/
        String departname = "";/*服务商*/
        String expecttime = "";/*预计到货时间*/
        String gettime = "";/*签收时间*/
        boolean f = false;
        SimpleDateFormat sf = new SimpleDateFormat("YYYY-MM-dd");
        SimpleDateFormat sftime = new SimpleDateFormat("YYYY-MM-dd HH:ss");
        CbsInspectionEvaluateEntity evaluateEntity = systemService.get(CbsInspectionEvaluateEntity.class, oConvertUtils.getString(id));
        if (type.equals(StaticValue.DIC_EVALUATE_BUS_TYPE_1)) {  //巡检
            mv = new ModelAndView("com/wx/personal_center/my_inspection/pc_inspection_evaluate");
            if (evaluateEntity != null && !StringUtils.isEmpty(evaluateEntity.getInspection().getCompany())) {
                List<TSDepart> departs = cbsInspectionAppointmentService.findHql("from TSDepart where orgCode=?", evaluateEntity.getInspection().getCompany());
                if (departs.size() > 0) {
                    mv.addObject("depart", departs.get(0));
                }
            }
        }
        if (type.equals(StaticValue.DIC_EVALUATE_BUS_TYPE_2)) {  //维修
            f = true;
            mv = new ModelAndView("com/wx/personal_center/my_inspection/pc_service_servicing");
        }
        if (type.equals(StaticValue.DIC_EVALUATE_BUS_TYPE_3)) {  //投诉
            f = true;
            mv = new ModelAndView("com/wx/personal_center/my_inspection/pc_service_complain");
        }
        if (type.equals(StaticValue.DIC_EVALUATE_BUS_TYPE_4)) {  //其他
            f = true;
            mv = new ModelAndView("com/wx/personal_center/my_inspection/pc_service_other");
        }
        if (f && StringUtil.isNotEmpty(evaluateEntity)) {
            if (StringUtil.isNotEmpty(evaluateEntity.getCbsService())) {   /*默认生成的服务单，服务单id肯定不为空*/
                zyCinemaName = evaluateEntity.getCbsService().getZyCinemaName();
                zyCinemaAddress = evaluateEntity.getCbsService().getAddress();
                endTime = StringUtil.isNotEmpty(evaluateEntity.getCbsService().getCloseTime()) ? sf.format(evaluateEntity.getCbsService().getCloseTime()) : "";
                engineer = StringUtil.isNotEmpty(evaluateEntity.getCbsService().getEngineer()) ? systemService.get(ZyEngineerEntity.class, evaluateEntity.getCbsService().getEngineer()).getName() : "";
                departname = StringUtil.isNotEmpty(evaluateEntity.getCbsService().getZyContacts()) ? systemService.get(ZyContactsEntity.class, evaluateEntity.getCbsService().getZyContacts()).getBelongOrg().getDepartname() : "";
                String cr = evaluateEntity.getCbsService().getCode();
                //发货单
                List<CbsDelinerEntity> CbsDeliver = systemService.findByQueryString("from CbsDelinerEntity where crCode = '" + cr + "' and status = '7'");
                if (CbsDeliver != null && CbsDeliver.size()>0) {
                	expecttime = StringUtil.isNotEmpty(CbsDeliver.get(0).getExpectTime()) ? sftime.format(CbsDeliver.get(0).getExpectTime()) : "";
                	gettime = StringUtil.isNotEmpty(CbsDeliver.get(0).getGetTime()) ? sftime.format(CbsDeliver.get(0).getGetTime()) : "";
                	StringBuffer strBuffer = new StringBuffer(expecttime);
                	StringBuffer strBuffer2 = new StringBuffer(gettime);
                	for (int i = 1; i<CbsDeliver.size();i++){
                		 strBuffer.append("/");
                		 strBuffer.append(StringUtil.isNotEmpty(CbsDeliver.get(i).getExpectTime()) ? sftime.format(CbsDeliver.get(i).getExpectTime()) : "");
                		 strBuffer2.append("/");
                		 strBuffer2.append(StringUtil.isNotEmpty(CbsDeliver.get(i).getGetTime()) ? sftime.format(CbsDeliver.get(i).getGetTime()) : "");
                	}
                	expecttime = strBuffer.toString();
                	gettime=strBuffer2.toString();
                }
            } else if (StringUtil.isNotEmpty(evaluateEntity.getCbsCode())) {  /*手动创建的服务单，服务单id为空，服务单code不为空*/
                CbsServiceEntity cbsServiceEntity = systemService.findUniqueByProperty(CbsServiceEntity.class, "code", evaluateEntity.getCbsCode());
                if (StringUtil.isNotEmpty(evaluateEntity.getCinemaName())) {
                    ZyCinemaEntity zyCinemaEntity = systemService.get(ZyCinemaEntity.class, evaluateEntity.getBelongCinemaId());
                    zyCinemaName = zyCinemaEntity.getName();
                    zyCinemaAddress = zyCinemaEntity.getAddress();
                }
                if (StringUtil.isNotEmpty(cbsServiceEntity)) {
                    endTime = StringUtil.isNotEmpty(cbsServiceEntity.getCloseTime()) ? sf.format(cbsServiceEntity.getCloseTime()) : "";
                    engineer = StringUtil.isNotEmpty(cbsServiceEntity.getEngineer()) ? systemService.get(ZyEngineerEntity.class, cbsServiceEntity.getEngineer()).getName() : "";
                    departname = StringUtil.isNotEmpty(cbsServiceEntity.getZyContacts()) ? systemService.get(ZyContactsEntity.class, cbsServiceEntity.getZyContacts()).getBelongOrg().getDepartname() : "";
                }
            } else {  /*手动创建的服务单，服务单code为空的情况*/
                zyCinemaName = evaluateEntity.getCinemaName();

                //查询影院地址
                List<ZyCinemaEntity> zyCinemaEntity = systemService.findByQueryString("from ZyCinemaEntity where name like '%" + zyCinemaName + "%'");
                if (zyCinemaEntity.size() > 0) {
                    zyCinemaAddress = zyCinemaEntity.get(0).getAddress();
                }

            }
            mv.addObject("zyCinemaName", zyCinemaName);
            mv.addObject("zyCinemaAddress", zyCinemaAddress);
            mv.addObject("endTime", endTime);
            mv.addObject("engineer", engineer);
            mv.addObject("departname", departname);
            mv.addObject("expecttime", expecttime);
            mv.addObject("gettime", gettime);
        }
        mv.addObject("evaluate", evaluateEntity);
        return mv;
    }

    @RequestMapping(params = "goInspectionEvaluate")
    public ModelAndView goInspectionEvaluate(String inspectionId, HttpServletRequest request) {
        request.setAttribute("inspectionId", inspectionId);
        ZyInspectionPlanEntity plan = systemService.get(ZyInspectionPlanEntity.class, inspectionId);
        request.setAttribute("plan", plan);
        request.setAttribute("evaluate", plan.getEvaluate());
        return new ModelAndView("com/wx/personal_center/my_inspection/inspection_evaluate");
    }

    @RequestMapping(params = "doEvalute")
    @ResponseBody
    public AjaxJson doEvalute(CbsInspectionEvaluateEntity evalute) {
        AjaxJson result = new AjaxJson();
        try {
            //巡检评价记录是在 工程师保存巡检报告之后创建的一条评分为0的记录，所以此处的id理论不可能为空
            if (!StringUtil.isEmpty(evalute.getId())) {
                CbsInspectionEvaluateEntity storedEvaluate = cbsInspectionEvaluateService.get(CbsInspectionEvaluateEntity.class, evalute.getId());
                MyBeanUtils.copyBeanNotNull2Bean(evalute, storedEvaluate);
                cbsInspectionEvaluateService.doEvalute(storedEvaluate);
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    @RequestMapping(params = "canUpdatePlanDate")
    @ResponseBody
    public AjaxJson canUpdatePlanDate(String planId) {
        AjaxJson re = new AjaxJson();
        ZyInspectionPlanEntity plan = systemService.get(ZyInspectionPlanEntity.class, planId);
        if (plan == null) {
            re.setSuccess(false);
            return re;
        } else {
            ZyInspectionPlanServiceImpl.UpdateOrdertimeReason reason = zyInspectionPlanService.checkIfCanUpdateEngineerOrderTime(plan, "");
            re.setSuccess(reason.isCanUpdate());
            re.setMsg(reason.getMsg());
            return re;
        }
    }

    @RequestMapping(params = "goInspectionDetail")
    public String goInspectionDetail(ModelMap modelMap, String id) {
        ZyInspectionPlanEntity plan = zyContractsService.get(ZyInspectionPlanEntity.class, id);
        if (plan != null) {
            modelMap.put("plan", plan);
            modelMap.put("state", assembleState(plan));
            if (StaticValue.DIC_PLAN_STATE_INSPECTION_CANCEL.equals(plan.getState())) {
                List<ZyPlanRecordEntity> records = zyContractsService.findHql("from ZyPlanRecordEntity where busId=? and planState=?", plan.getId(), plan.getState());
                if (records.size() > 0) {
                    modelMap.put("cancelReason", records.get(0).getRemark());
                }
            }
            List<ZyInspectionReportEntity> report = zyContractsService.findByProperty(ZyInspectionReportEntity.class, "inspectionPlanId", plan.getId());
            if (report != null && report.size() > 0) {
                modelMap.put("report", report.get(0));
            }
        }
//        comprehensiveEvaluation
        return "com/wx/personal_center/my_inspection/inspection_detail";
    }

    public Map assembleState(ZyInspectionPlanEntity plan) {
        Map m = new HashMap();
        String planStateText = "", planDate = "";
        String state = plan.getState();
        if (StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE.equals(state)) {
            planStateText = "已完成";
            planDate = null != plan.getEndTime() ? DateUtils.formatDate(plan.getEndTime(), "yyyy-MM-dd") : "";
        } else if (StaticValue.DIC_PLAN_STATE_INSPECTION_CANCEL.equals(state)) {
            planStateText = "已取消";
            planDate = null != plan.getUpdateDate() ? DateUtils.formatDate(plan.getUpdateDate(), "yyyy-MM-dd") : "";
        } else if (StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY.equals(state)
                || StaticValue.DIC_PLAN_STATE_THIRDPARTY_REFUSED.equals(state)
                || StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED.equals(state)
                || StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED.equals(state)
                || StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED.equals(state)
                || StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED.equals(state)) {
            planStateText = "巡检准备中";
            planDate = null != plan.getCreateDate() ? DateUtils.formatDate(plan.getCreateDate(), "yyyy-MM-dd") : "";
        } else if (StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED.equals(state)
                || StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT.equals(state)) {
            planStateText = "已预约";
            planDate = DateUtils.formatDate(plan.getEngineerOrderTime(), "yyyy-MM-dd");
        }
        m.put("planStateText", planStateText);
        m.put("planDate", planDate);
        return m;
    }

    @RequestMapping(params = "search")
    @ResponseBody
    public List<Map> search(String content, String type) {
        List<Map> results = new ArrayList<Map>();
        ZyContactsEntity ct = zyContractsService.findContactByUserName(ResourceUtil.getSessionUserName().getUserName());
        if (ct.getBelongCinema() != null) {
            if ("xjd".equals(type)) {
                List<ZyInspectionPlanEntity> plans = zyInspectionPlanService.queryPlanWithCinemaAndYear(ct.getBelongCinema().getId(), "");
                for (ZyInspectionPlanEntity plan : plans) {
                    if (!oConvertUtils.isEmpty(content) && !plan.getEquipmentSpare().getSn().contains(content)) {
                        continue;
                    }
                    /*不显示待处理和取消的*/
                    if (plan.getState().equals(StaticValue.DIC_PLAN_STATE_TODO)
                            || plan.getState().equals(StaticValue.DIC_PLAN_STATE_INSPECTION_CANCEL)) {
                        continue;
                    }
                    Map m = new HashMap();
                    m.put("id", plan.getId());
                    m.put("sn", plan.getEquipmentSpare().getSn());
                    m.put("ipPlanDate", DateUtils.date2Str(plan.getIpPlanDate(), DateUtils.date_sdf));
                    m.put("engineerOrderTime", DateUtils.date2Str(plan.getEngineerOrderTime(), DateUtils.date_sdf));
                    if (plan.getEquipmentSpare().getType() != null) {
                        m.put("typeDesc", oConvertUtils.getString(plan.getEquipmentSpare().getType().getTypeDesc()));
                    }
                    if (plan.getEquipmentSpare().getHouse() != null) {
                        m.put("roomNum", plan.getEquipmentSpare().getHouse().getRoomNum());
                    }
                    m.put("state", plan.getState());
                    String planStateText = "", planDate = "";
                    String state = plan.getState();
                    m.putAll(assembleState(plan));
                    m.put("stateText", systemService.getTypeByCode("planState", plan.getState()));
                    m.put("endTime", plan.getEndTime() == null ? "" : DateUtils.formatDate(plan.getEndTime(), "yyyy-MM-dd"));
                    m.put("canEval", plan.getEvaluate() != null && StaticValue.DIC_EVALUATE_STATE_0.equals(plan.getEvaluate().getEvaluateState()));
                    m.put("evaluate", plan.getEvaluate() != null && "1".equals(plan.getEvaluate().getEvaluateState()) ? plan.getEvaluate().getId() : "");
                    results.add(m);
                }
            }
        }
        return results;
    }

    @RequestMapping(params = "confirmOrderTime")
    @ResponseBody
    public AjaxJson confirmOrderTime(String inspectionId) {
        AjaxJson result = new AjaxJson();
        result.setSuccess(false);
        ZyInspectionPlanEntity plan = systemService.get(ZyInspectionPlanEntity.class, oConvertUtils.getString(inspectionId));
        if (plan != null) {
            result.setSuccess(true);
            plan.setConfirmOrderTime(1);
            systemService.updateEntitie(plan);
        }
        return result;
    }

    @RequestMapping(params = "list")
    public String list(ModelMap modelMap) {

        if (ResourceUtil.getSessionUserName() == null || !ResourceUtil.getSessionUserName().ifGoldMedal()) {
            return "redirect:wxMenuController.do?xjyy";
        }

        List<ZyEquipmentSpareEntity> equips = zyEquipmentSpareService.findEquipByUserName(ResourceUtil.getSessionUserName().getUserName());
        modelMap.put("equips", equips);
        modelMap.put("equipCount", equips.size());
        int inService = 0;
        if (equips.size() > 0) {
            String ids = "";
            for (ZyEquipmentSpareEntity eq : equips) {
                ids += "," + eq.getId();
                if (eq.getRepairEndDate() != null && eq.getRepairEndDate().after(new Date())) {
                    inService++;
                }
            }
            modelMap.put("ids", ids.substring(1));
            /*CbsPartInfoController cpi = new CbsPartInfoController();
            modelMap.put("cpi",cpi.getEquipmentIdById(oConvertUtils.getString(modelMap.get("ids"))));*/
        }
        modelMap.put("serviceCount", inService);
        modelMap.put("year", Calendar.getInstance().get(Calendar.YEAR));
        return PREFIX + "/xjyy/list";
    }

    @RequestMapping(params = "goSign")
    public String goSign(String ids, String types, ModelMap modelMap) {
        modelMap.put("contact", zyContractsService.findContactByUserName(ResourceUtil.getSessionUserName().getUserName()));
        if (oConvertUtils.isNotEmpty(ids)) {
            modelMap.put("equipIds", ids);
            modelMap.put("types", types);
            modelMap.put("years", cbsInspectionAppointmentService.generateExpectYearsSelect());
            return PREFIX + "/xjyy/sign";
        } else {
            return PREFIX + "/xjyy/list";
        }

    }


    /**
     * 添加巡检预约
     *
     * @return
     */
    @RequestMapping(params = "doSign")
    @ResponseBody
    public AjaxJson doSign(CbsInspectionAppointmentEntity cbsInspectionAppointment, HttpServletRequest request, String equipmentIdStr, String equipmentTypeStr) {
        AjaxJson j = new AjaxJson();
        String message = "巡检预约添加成功";
        try {
            cbsInspectionAppointment.setInAppId(cbsInspectionAppointmentService.genInAppId(cbsInspectionAppointment));

            cbsInspectionAppointmentService.save(cbsInspectionAppointment);

            String equipmentIds[] = equipmentIdStr.split(",");
            String equipmentTypes[] = equipmentTypeStr.split(",");
            List<CbsInspectionAppointmentEsEntity> esList = new ArrayList<CbsInspectionAppointmentEsEntity>();
            String cinema = "";
            for (int i = 0; i < equipmentIds.length; i++) {
                CbsInspectionAppointmentEsEntity es = new CbsInspectionAppointmentEsEntity();
                ZyEquipmentSpareEntity equip = systemService.get(ZyEquipmentSpareEntity.class, equipmentIds[i]);
                if (equip != null && equip.getZyCinema() != null) {
                    cinema = equip.getZyCinema().getName();
                }
                es.setEs(equip);
                es.setInspectionAppointment(cbsInspectionAppointment);
                es.setType(equipmentTypes[i]);
                esList.add(es);
            }
            systemService.batchSave(esList);
            // 0.草稿 1.提交 3.取消,4 处理中
            if ("0".equals(cbsInspectionAppointment.getStatus())) {
//				cbsInspectionAppointment
//                ProcessInstance inst = zyWorkFlowService.startOnlineProcess("cbs_inspection_appointment", cbsInspectionAppointment.getId(), new HashMap<String, Object>());
//                zyWorkFlowService.goProcessNode(cbsInspectionAppointment.getId(), StaticValue.CBS_INSPECTION_APPOINTMENT_FLOW_KEY, "taskNode0", "taskNode1");
//                Task task = taskService.createTaskQuery().processInstanceId(inst.getProcessInstanceId()).active().singleResult();
//                TSUser user = ResourceUtil.getSessionUserName();
//                zyPlanRecordService.savePlanRecord(cbsInspectionAppointment.getId(), inst.getProcessInstanceId(), task.getId(), "", user.getUserName(), message);

                //// TODO: 2016/10/31 給hd發送郵件提醒
                ZyEmailEntity eMail = new ZyEmailEntity();
                eMail.setEmailSubject("<" + cinema + ">巡检服务申请");
                eMail.setEmailReceiver(StaticValue.COMMON_EMAIL_ADDRESS);

                Map<String, Object> rejectMap = new HashMap<String, Object>();
                //String subject = "<" + cbsInspectionAppointment.getCinema().getName() + ">巡检服务申请";
                rejectMap.put("cinemaName", cinema);
                rejectMap.put("inAppId", cbsInspectionAppointment.getInAppId());
                rejectMap.put("url", StaticValue.HTTP_HEADER);
                // TODO 由于给系统用户发送   暂屏蔽掉
                SendMailUtil.sendFtlMail(eMail, "sms_wxAppointHd_approval.ftl", rejectMap, systemService);
            }
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
            zyPlanRecordService.savePlanRecord(cbsInspectionAppointment.getId(), "", "", "", ResourceUtil.getSessionUserName().getUserName(), "微信端预约巡检服务" + cbsInspectionAppointment.getInAppId());

        } catch (Exception e) {
            e.printStackTrace();
            message = "巡检预约添加失败";
        }
        j.setMsg(cbsInspectionAppointment.getInAppId());
        return j;
    }

    @RequestMapping(params = "getAppointment")
    @ResponseBody
    public List<Map> getAppointmentByUserCinema(String searchContent) {
        List<Map> results = new ArrayList<Map>();
        ZyContactsEntity contact = zyContractsService.findContactByUserName(ResourceUtil.getSessionUserName().getUserName());
        if (contact.getBelongCinema() != null) {
            List<CbsInspectionAppointmentEntity> apps = new ArrayList<CbsInspectionAppointmentEntity>();
            if (oConvertUtils.isEmpty(searchContent)) {
                apps = cbsInspectionAppointmentService.findAppointmentWithCinema(contact.getBelongCinema().getId());
            } else {
                apps = cbsInspectionAppointmentService.findAppointmentWithCinemaAndSn(contact.getBelongCinema().getId(), searchContent);
            }
            for (CbsInspectionAppointmentEntity app : apps) {
                results.add(cbsInspectionAppointmentService.genMapVo(app));
            }
        }
        return results;
    }

    @RequestMapping(params = "goAppointDetail")
    public String goAppointDeail(String appointId, ModelMap modelMap) {
        modelMap.put("app", cbsInspectionAppointmentService.get(CbsInspectionAppointmentEntity.class, oConvertUtils.getString(appointId)));
        return "com/wx/personal_center/my_inspection/appointment_detail";
    }

    @RequestMapping(params = "updateIpPlandate")
    @ResponseBody
    public AjaxJson updateIpPlanDate(String id, String planDate) {
        AjaxJson result = new AjaxJson();
        result.setSuccess(false);
        ZyInspectionPlanEntity plan = zyInspectionPlanService.get(ZyInspectionPlanEntity.class, oConvertUtils.getString(id));
        if (plan != null) {
            ZyInspectionPlanServiceImpl.UpdateOrdertimeReason re = zyInspectionPlanService.updatePlanDate(plan, planDate);
            result.setSuccess(re.isCanUpdate());
            result.setMsg(re.getMsg());
        }
        return result;
    }

    /**
     * 跳转评价单页面
     *
     * @return
     */
    @RequestMapping(params = "goCreateEvaluate")
    public ModelAndView goCreateEvaluate() {
        return new ModelAndView("com/zybk/cbs_evaluate/evaluate-add");
    }

    @RequestMapping(params = "doFindType")
    @ResponseBody
    public AjaxJson doFindType(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        String ServiceId = request.getParameter("ServiceId");
        String type = "other";
        boolean flag = true;
        List<CbsInspectionEvaluateEntity> cbsInspectionEvaluate = systemService.findByProperty(CbsInspectionEvaluateEntity.class, "cbsCode", ServiceId);
        if (cbsInspectionEvaluate.size() > 0) {
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("单号已存在！");
        } else {
            List<ZyInspectionPlanEntity> plan = zyInspectionPlanService.findByProperty(ZyInspectionPlanEntity.class, "planId", oConvertUtils.getString(ServiceId));
            if (plan.size() > 0) {
                //巡检类型
                type = "xunj";
                flag = false;
            }
            if (flag) {   //防止已经是巡检类型的，再次查找一次，影响查找速度
                List<CbsServiceEntity> cbsServiceList = systemService.findByProperty(CbsServiceEntity.class, "code", ServiceId);
                if (cbsServiceList.size() > 0) {
                    for (CbsServiceEntity cbsServiceEntity : cbsServiceList) {
                        List<CbsInspectionEvaluateEntity> cbsInspectionEvaluates = systemService.findByProperty(CbsInspectionEvaluateEntity.class, "cbsService.id", cbsServiceEntity.getId());
                        if (cbsInspectionEvaluates.size() > 0) {
                            ajaxJson.setSuccess(false);
                            ajaxJson.setMsg("单号已存在！");
                        } else {
                            if (cbsServiceEntity.getServiceType1().getName().contains("维修") || cbsServiceEntity.getServiceType2().getName().contains("维修")) {
                                type = "weix";
                            }
                            if (cbsServiceEntity.getServiceType1().getName().contains("投诉") || cbsServiceEntity.getServiceType2().getName().contains("投诉")) {
                                type = "tous";
                            }
                        }
                    }
                }
            }
        }


        Map map = new HashMap();
        map.put("type", type);
        ajaxJson.setAttributes(map);
        return ajaxJson;
    }

    /**
     * 创建评价单
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        TSUser user = ResourceUtil.getSessionUserName();
        String code = request.getParameter("code");
        String busType = request.getParameter("busType"); //服务类型
//        String cinemaName = request.getParameter("name");  //影院名称 取不到值，下面由影院id获取
        String belongCinemaId = request.getParameter("belongCinemaId"); //影院id
        String linkman = request.getParameter("linkman");
        String linkphone = request.getParameter("linkphone");
        String remark = request.getParameter("remark");

        if (StringUtil.isNotEmpty(code) && cbsInspectionEvaluateService.getIsTrue(code)) {
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("服务单的回访任务已经存在！");
        } else {
            boolean flag = true;
            CbsInspectionEvaluateEntity cie = new CbsInspectionEvaluateEntity();
            if (StringUtil.isNotEmpty(code)) {
                List<CbsServiceEntity> cbs = systemService.findByProperty(CbsServiceEntity.class, "code", code);
                if (cbs.size() > 0) {
                    cie.setCbsCode(code);
                } else {
                    flag = false;
                    ajaxJson.setSuccess(false);
                    ajaxJson.setMsg("服务单不存在，请核对服务单号！");
                }
            }
            if (flag) {
                ZyCinemaEntity zyCinemaEntity = systemService.get(ZyCinemaEntity.class, belongCinemaId);
                cie.setBelongCinemaId(belongCinemaId);
                cie.setCinemaName(StringUtil.isNotEmpty(zyCinemaEntity) ? zyCinemaEntity.getName() : "");
                cie.setLinkman(linkman);
                cie.setLinkphone(linkphone);
                cie.setRemark(remark);
                cie.setEffectEvaluate(0);
                cie.setLastEvaluate(0);
                cie.setServiceEvaluate(0);
                cie.setSkillEvaluate(0);
                cie.setTalkEvaluate(0);
                cie.setTrainEvaluate(0);
                cie.setBusType(busType);
                cie.setEvaluateState(StaticValue.DIC_EVALUATE_STATE_0);
                systemService.saveOrUpdate(cie);
            }
        }
        return ajaxJson;
    }

}
